package com.logic.idevice.impl.kv7

import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleEventObserver
import com.logic.idevice.IUHFScan
import com.sinopec.basemodule.constants.PreferencesConstant
import com.sinopec.basemodule.dialog.TankerProgressDialog
import com.uhf.api.cls.Reader
import com.uhf.uhf.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.iso88591.uhfg.*
import me.iso88591.uhfg.common.KEY_CODE_TRIGGER_K71
import me.iso88591.uhfg.common.keyCallBack

class Kv7Scan(
    override val callRefreshText: IUHFScan.IRefreshSpeed,
    override val callDataRefresh: IUHFScan.IRefreshData,
    override val callScanStatusChange: IUHFScan.IScanStatus,
    private val coroutineScope: CoroutineScope,
) : IUHFScan {

    private lateinit var lifecyUHFG: LifecycleUHFG

    private lateinit var loading: TankerProgressDialog

    override fun init(activity: AppCompatActivity) {

        loading = TankerProgressDialog(activity, R.style.CustomDialog)
        loading.setCanceledOnTouchOutside(false)

        lifecyUHFG = LifecycleUHFG(
            UHFGConfig(
                Kv7Setting.pow,
                Reader.Region_Conf.RG_PRC,
                false
            ),
            converter = IReadConverter { taginfo ->
                //先用 epc 后用user
                if (Kv7Setting.useEpcFlag == Kv7Setting.Companion.ScanAreaFlag.EPC) {
                    //PreferencesConstant.getInstance().setRfid_regex(replaceAll);
                    taginfo.epcStr(
                        onAppend = ReadTagInfoParse.TwoDigitsOneSpace,
                        rule = PreferencesConstant.getInstance().rfid_regex
                    )
                } else {
                    taginfo.embStr(
                        onAppend = ReadTagInfoParse.TwoDigitsOneSpace,
                        rule = PreferencesConstant.getInstance().rfid_regex
                    )
                }
            },
        ) { uhfg, manager ->
            if (manager != null) {
                loading.dismiss()

                launch {
                    uhfg.readerController.readData.collectLatest {
                        callDataRefresh.onRefreshData(it)
                        callRefreshText.onRefreshSpeed(
                            it.size,//uhfg.readerController.currentReadingCount,
                            uhfg.readerController.speed,
                            uhfg.readerController.readingTimeSum / 1000,
                        )
                    }
                }

                launch {
                    uhfg.readerController.readStatusFlow.collect {
                        callScanStatusChange.onScanStatusChange(it)
                    }
                }

            }

            activity.apply {
                keyCallBack(activity) { isDown, it ->
                    if (KEY_CODE_TRIGGER_K71 == it) {

                        /**
                         * create by lwj at 2022/7/20
                         * !!! 调用 onkeydown的原因是
                         *
                         *? common型设备 通过系统的 onKeyDown获取到 手持扳机的扣动事件
                         *
                         ** event -> onKeyDown
                         *
                         *? kv7型设备 则是通过特定的广播回调来执行的
                         *
                         ** broadCastReceiver ->  自己生成一个 event  -> onKeyDown
                         *
                         *
                         */
                        if (isDown) {
                            activity.onKeyDown(
                                it,
                                KeyEvent(
                                    KeyEvent.ACTION_DOWN,
                                    it
                                )
                            )
                        } else {
                            activity.onKeyUp(
                                it,
                                KeyEvent(
                                    KeyEvent.ACTION_UP,
                                    it
                                )
                            )
                        }

                    }
                }
            }
        }

        activity.lifecycle.addObserver(LifecycleEventObserver{source, event ->
            try {
                lifecyUHFG.onStateChanged(source, event)
            } catch (e: Exception) {
                e.printStackTrace()
                loading.dismiss()
            }
        })
        lifecyUHFG.onInitSdk = {
            loading.setText("连接设备")
            loading.show()
        }

    }

    override fun startOrStop(isStart: Boolean) {
        if (isStart) {
            lifecyUHFG.readerController.loopRead(
                if (Kv7Setting.useEpcFlag == Kv7Setting.Companion.ScanAreaFlag.EPC)
                    ReadController.BANK_EPC
                else ReadController.BANK_USER,
                coroutineScope)
        } else {
            coroutineScope.launch {
                launch {
                    try {
                        lifecyUHFG.readerController.cancel(this)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    override fun isCloseRfid(): Boolean {
        return true
    }

    override fun isScanning(): Boolean {
        return lifecyUHFG.readerController.readStatus
    }

    override fun clear() {
        coroutineScope.launch {
            lifecyUHFG.readerController.suspendClear()
        }
    }

    override fun newestData(): List<String> {
        return emptyList()//lifecyUHFG.readerController.read()
    }
}